<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="filters">
				<el-form-item>
					<el-input v-model="filters.name" placeholder="员工姓名"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="query">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>
    <!--username
          email
          phone
          salt
          password
          age
          state
-->
		<!--列表-->
		<el-table :data="employees" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
			<el-table-column type="selection" width="55">
			</el-table-column>
			<el-table-column type="index" width="60">
			</el-table-column>
			<el-table-column prop="username" label="员工姓名" width="120" sortable>
			</el-table-column>
      <el-table-column prop="email" label="邮箱" width="150" sortable>
      </el-table-column>
      <el-table-column prop="phone" label="电话" width="150" sortable>
      </el-table-column>
      <el-table-column prop="salt" label="盐值" width="150" sortable>
      </el-table-column>
      <el-table-column prop="password" label="密码" width="150" sortable>
        <template slot-scope="scope">
          <span>*********</span>
        </template>
      </el-table-column>
      <el-table-column prop="age" label="年龄" width="100" sortable>
      </el-table-column>
      <el-table-column prop="state" label="状态" width="100" sortable>
        <template slot-scope="scope">
          <span v-if="scope.row.state == 1" style="color: #42d885">
            正常
          </span>
          <span v-else style="color:red;">
            禁用
          </span>
        </template>
      </el-table-column>
			<el-table-column label="操作">
				<template scope="scope">
					<el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
					<el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!--工具条-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger"
                 @click="batchRemove"
                 :disabled="this.sels.length===0">批量删除</el-button>
			<el-pagination layout="prev, pager, next"
                     @current-change="handleCurrentChange"
                     :page-size="pageSize"
                     :current-page="currentPage"
                     :total="total"
                     style="float:right;">
			</el-pagination>
		</el-col>


		<!--编辑界面
		username
          email
          phone
          salt
          password
          age
          state
		-->
		<el-dialog :title="title"  :visible.sync="editFormVisible" :close-on-click-modal="false" @close="closeFresh">
			<el-form :model="editForm" label-width="80px" :rules="editFormRules" ref="editForm">
				<el-form-item label="姓名" prop="username">
					<el-input v-model="editForm.username" auto-complete="off"></el-input>
				</el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="editForm.phone" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="editForm.password" auto-complete="off" show-password></el-input>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input v-model="editForm.age" auto-complete="off"></el-input>
        </el-form-item>
				<el-form-item label="状态">
					<el-radio-group v-model="editForm.state">
						<el-radio class="radio" :label="1">正常</el-radio>
						<el-radio class="radio" :label="0">禁用</el-radio>
					</el-radio-group>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="editFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
			</div>
		</el-dialog>
	</section>
</template>

<script>
	import util from '../../common/js/util'
	//import NProgress from 'nprogress'
	import { getUserListPage, removeUser, batchRemoveUser, editUser, addUser } from '../../api/api';

	export default {
		data() {
			return {
				filters: {
					name: ''
				},
        employees:[],//员工数据
        deptTree:[],//部门树
				total: 0,//总条数
				currentPage: 1,//当前页
        pageSize:5,//显示的条数
				listLoading: false,
				sels: [],//列表选中列
        //编辑
				editFormVisible: false,//编辑界面是否显示
        title:'',
				editLoading: false,
				editFormRules: {//校验规则
					username: [
						{ required: true, message: '用户名不能为空', trigger: 'blur' }
					],
          password: [
            { required: true, message: '密码不能为空', trigger: 'blur' }
          ],
          phone: [
            { required: true, validator:this.phoneRules, trigger: 'blur' }
          ],
          email: [
            { required: true, validator:this.checkEmail, trigger: 'blur' }
          ],
				},
				//编辑界面数据
				editForm: {
					id: null,
          username: '',
          email: '',
          phone:'',
          salt:'',
          password:'',
          age:'',
          state:1,
				},
			}
		},
		methods: {
      closeFresh(){
        this.$refs['editForm'].resetFields();
      },
		  //邮箱校验
      checkEmail(rule, value, callback){
        const mailReg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/
        if (!value) {
          return callback(new Error('邮箱不能为空'))
        }
        setTimeout(() => {
          if (mailReg.test(value)) {
            callback()
          } else {
            callback(new Error('请输入正确的邮箱格式'))
          }
        }, 100)
      },
		  //手机校验
      phoneRules(rule, value, callback){
          if (value === '') {
            callback(new Error('手机号不能为空'))
          } else if (!/^1\d{10}$/.test(value)) {
            callback(new Error('手机号格式错误'))
          } else {
            callback()
          }
      },


			handleCurrentChange(val) {
				this.currentPage = val;
				this.getEmployees();
			},
      query(){
			  //定位到第一页
        this.currentPage=1;
        this.getEmployees();
      },

			/*//获取用户列表
			getDepartments() {
        //封装参数
				let para = {
          currentPage: this.currentPage,
          pageSize:this.pageSize,
          search: this.filters.name
				};
				//加载忙等框
				this.listLoading = true;
        //发送axios
        this.$http.post("/dept",para)
        .then(result=>{//发送请求成功
          //关闭忙等框
          this.listLoading = false;
          //console.log(result);
          result=result.data;
          this.employee=result.rows;
          this.total=result.total;
        })
        .catch(result=>{//发送请求失败
          this.$message({
            message: '请求失败',
            type: 'error'
          });
        })
			},*/
			//删除
			handleDel: function (index, row) {
				this.$confirm('确认删除该记录吗?', '提示', {
					type: 'warning'
				}).then(() => {//确定删除
					this.listLoading = true;
					//NProgress.start();
					//发送请求
          this.$http.delete("/employee/"+row.id)
          .then(result=>{//请求成功
            this.listLoading = false;
            //console.log(result)
            result=result.data;
              if(result.success){
                this.$message({
                  message: '删除成功',
                  type: 'success'
                });
                this.getEmployees();
              }else {
                result.msg
              }
          })
          .catch(result=>{//请求失败
            this.listLoading = false;
            this.$message({
              message: '系统异常',
              type: 'error'
            });
          })
				}).catch(() => {//取消删除

				});
			},

			//显示编辑界面
			handleEdit: function (index, row) {
			  //打开模态框
				this.editFormVisible = true;
				this.title="编辑";
				this.editForm = Object.assign({}, row);
				//回显上级部门
       /* this.getDeptTree();
        if(this.editForm.dirPath){
          let arr=this.editForm.dirPath.split("/");
          let arrPath=[];
          for(let i=1;i<=arr.length-2;i++){
            console.log(arr[i]);
              arrPath.push(parseInt(arr[i]));
          }
          this.editForm.parent=arrPath;
        }*/
			},
			//显示新增界面
			handleAdd: function () {
				this.editFormVisible = true;
        this.title="新增";
				this.editForm = {
          id: null,
          username: '',
          email: '',
          phone:'',
          salt:'',
          password:'',
          age:'',
          state:1,
				};
			},

			//编辑
			editSubmit: function () {
			  //获取ref中的名叫editForm的对象
				this.$refs.editForm.validate((valid) => {
				  //validate效验规则
					if (valid) {
						this.$confirm('确认提交吗？', '提示', {}).then(() => {
						  //按钮忙等框
							this.editLoading = true;
							//NProgress.start();
              //克隆获取的表单数据
							let para = Object.assign({}, this.editForm);
							//对parent做一个处理
              /*if(para.parent){
                //将parent数组转换为对象 para.parent.length-1相当于取得下标
                para.parent={"id":para.parent[para.parent.length-1]}
              }*/

							//发送请求
              this.$http.put("/employee",para)
                  .then(result=>{//请求成功
                    //关闭按钮忙等框
                    this.editLoading = false;
                    //关闭模态框
                    this.editFormVisible = false;
                    result=result.data;
                    if(result.success){
                      this.$message({
                        message: '操作成功',
                        type: 'success'
                      });
                    }
                    //刷新页面
                    this.query();
                  })
                  .catch(result=>{//请求失败
                    //关闭按钮忙等框
                    this.editLoading = false;
                    this.$message({
                      message: '系统异常',
                      type: 'error'
                    });
                  })
						});
					}
				});
			},
			selsChange: function (sels) {
				this.sels = sels;
			},
			//批量删除
			batchRemove: function () {
			  //获取当前项的id
				var ids = this.sels.map(item => item.id);
				this.$confirm('确认删除选中记录吗？', '提示', {
					type: 'warning'
				}).then(() => {//确定按钮
				  //开启忙等框
					this.listLoading = true;
					//NProgress.start();
					this.$http.patch("/employee",ids)
          .then(result=>{//请求成功
            //关闭忙等框
            this.listLoading = false;
            result=result.data;
            if(result.success){
              this.$message({
                message: '删除成功',
                type: 'success'
              });
            }
            //刷新页面
            this.query();
          })
					.catch(result=>{//请求失败
            this.$message({
              message: '系统异常',
              type: 'error'
            });
          })
				}).catch(() => {//取消

				});
			},
      //查询员工数据
      getEmployees(){
        //封装参数
        let para = {
          currentPage: this.currentPage,
          pageSize:this.pageSize,
          search: this.filters.name
        };
        //加载忙等框
        this.listLoading = true;
        //发送axios
        this.$http.post("/employee",para)
            .then(result=>{//发送请求成功
              //关闭忙等框
              this.listLoading = false;
              //console.log(result);
              result=result.data;
              this.employees=result.rows;
              this.total=result.total;
            })
            .catch(result=>{//发送请求失败
              this.$message({
                message: '请求失败',
                type: 'error'
              });
            })
      },
      //查询部门树
      getDeptTree(){
        this.$http.get("/dept/tree")
            .then(result=>{
              result=result.data;
              this.deptTree=result;
             // console.log(result);
            })
      }
		},
		mounted() {
			this.getEmployees();
		}
	}

</script>

<style scoped>

</style>